﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Chowpoo.Common;
using CourseSystem.Core.BLL;
using CourseSystem.Core.Entities;

namespace CourseSystem.Stat
{
    public class IpStat
    {
        private static Dictionary<string, DateTime> _todayIpList;
        private static DateTime _lastUpdateTime = DateTime.Now;
        private static List<string> _ipList;
        private static int _hitsAdd = 0;
        public static int HitsAdd
        {
            get { return _hitsAdd; }
        }
        public static int HitsIPAdd
        {
            get { return _todayIpList == null ? 0 : _todayIpList.Count; }
        }
        static IpStat()
        {
            _ipList = new List<string>(30);
            LoadFromDb();
        }



        public static void LoadFromDb()
        {
            _todayIpList = new Dictionary<string, DateTime>(500);
            var list = TodayIpStatBLL.GetAll();
            foreach (var item in list)
            {
                if (_todayIpList.ContainsKey(item.Ip))
                    continue;
                _todayIpList.Add(item.Ip, item.LastTime);
            }
        }

        public static Dictionary<string, DateTime> GetLastIp()
        {
            return _todayIpList;
        }

        public static void IpStatDo()
        {
            var ip = CommonRequest.GetIP();
            if (string.IsNullOrEmpty(ip))
                return;
            var now = DateTime.Now;
            if (_todayIpList.ContainsKey(ip))
            {
                _todayIpList[ip] = now;
                return;
            }
            _todayIpList.Add(ip, now);
        }

        public static void UpdateStat()
        {
            //清理
            TodayIpStatBLL.DelAll();
            var add = new List<TodayIpStatInfo>(500);
            add.AddRange(_todayIpList.Keys.Select(item => new TodayIpStatInfo { Ip = item }));
            TodayIpStatBLL.Add(add);

            TodayIpStatBLL.UpdateStat(_hitsAdd, UserOnlineStat.GetOnlineCount());
            LoadFromDb();
            _hitsAdd = 0;
            CourseSettingBLL.GetFromDb();
        }

        public static void HitsStat()
        {
            Interlocked.Increment(ref _hitsAdd);
        }

    }


}
